#include "RingQueue.hpp"
#include <time.h>
#include <unistd.h>

#define P_COUNT 1
#define C_COUNT 1


RingQueue<int>* rq;

pthread_mutex_t c_lock;// 消费者的锁
pthread_mutex_t p_lock;// 生产者的锁

void* Consumer(void* arg)
{
  long id = (long)arg;
  //sleep(1);
  while (1){
    pthread_mutex_lock(&c_lock);
    // 消费（取）数据
    int data;
    rq->GetData(data);
    std::cout << "consumer " << id << " consumes a data: " << data << std::endl;
    pthread_mutex_unlock(&c_lock);
    sleep(1);
  }
}

void* Productor(void* arg)
{
  long id = (long)arg;
  //int data = 1;
  while (1){
    pthread_mutex_lock(&p_lock);
    // 生产（放）数据
    int data = rand()%10 + 1;
    //data = (data+1)%1;
    rq->PutData(data);
    std::cout << "productor " << id << " produncts a data: " << data << std::endl;
    pthread_mutex_unlock(&p_lock);
    //sleep(1);
  }
}
int main()
{
  srand((size_t)time(nullptr));
  pthread_mutex_init(&c_lock, nullptr);
  pthread_mutex_init(&p_lock, nullptr);

  // 创建一个交易场所
  rq =  new RingQueue<int>(10);
  //pthread_t p1, c1;
  pthread_t p[P_COUNT];
  pthread_t c[C_COUNT];

  for (long i = 0; i < P_COUNT; ++i)
  {
    pthread_create(p+i, nullptr, Productor, (void*)(i+1));
  }
  for (long i = 0; i < C_COUNT; ++i)
  {
    pthread_create(c+i, nullptr, Consumer, (void*)(i+1));
  }
  
  for (int i = 0; i < C_COUNT; ++i)
  {
    pthread_join(c[i], nullptr);
  }
  for (int i = 0; i < P_COUNT; ++i)
  {
    pthread_join(p[i], nullptr);
  }
  
  pthread_mutex_destroy(&c_lock);
  pthread_mutex_destroy(&p_lock);
  
  delete rq;
  return 0;
}
